<?php
/**
 * Created by PhpStorm.
 * User: august
 * Date: 2021/2/26
 * Time: 10:47
 */

namespace Aug\Tools;


class Tree
{
    private $data;

    /**
     * author: august 2021/2/26
     * @param array $data
     */
    public function __construct(array $data)
    {
        $this->data = $data;
    }

    /**
     * 获取树形数组
     * author: august 2021/2/26
     * @param int $topPid
     * @return array
     */
    public function getTreeArray($topPid = 0)
    {
        $tmp = [];
        foreach ($this->data as $data) {
            $tmp[$data['parent_id']][] = $data;
        }

        $treeData = [];
        if (!empty($tmp[$topPid])) {
            foreach ($tmp[$topPid] as $row) {
                $row['level'] = 0;
                $row['children'] = $this->_getChild($row, $tmp);
                $treeData[] = $row;
            }
        }

        return $treeData;
    }

    /**
     * 获取选项，主要用于下拉框
     * author: august 2021/2/26
     * @param int $level
     * @return array
     */
    public function getOptions($level = 3)
    {
        $flags = ['| ', '|--', '--'];
        $data = $this->getTreeArray();
        $optionData = [];
        foreach ($data as $row) {
            $prefix = $row['level'] === 0 ? $flags[0] : $flags[1];
            $optionData[$row['id']] = $prefix . $row['name'];
            if (!empty($row['children'])) {
                foreach ($row['children'] as $child) {
                    if ($child['level'] > $level) continue;
                    $_prefix = $flags[1] . str_repeat($flags[2], $child['level'] - 1);
                    $optionData[$child['id']] = $_prefix . $child['name'];
                }
            }
        }
        return $optionData;
    }

    /**
     * 获取所有后代
     * author: august 2021/2/26
     * @param $current 当前节点
     * @param $all 所有及诶单
     * @param int $level 等级
     * @return array
     */
    private function _getChild($current, $all, $level = 1)
    {
        $return = [];
        $children = empty($all[$current['id']]) ? [] : $all[$current['id']];
        if ($children) {
            foreach ($children as $child) {
                $child['level'] = $level;
                $return[] = $child;
                $res = $this->_getChild($child, $all, $level + 1);
                $return = array_merge($return, $res);
            }
        }

        return $return;
    }
}